<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    width="700px"
    @before-ok="save"
    @close="reset"
  >
    <div style="padding: 0 24px;">
      <GiForm ref="formRef" v-model="form" :options="options" :columns="columnsWithoutImage" />

      <a-form-item label="会议室图片" required>
        <template v-if="!form.imageUrl">
          <!-- 隐藏原生input，只显示按钮 -->
          <input
            ref="fileInputRef"
            type="file"
            accept="image/jpeg,image/png,image/jpg"
            style="display: none;"
            @change="handleImageUpload"
          />
          <a-button @click="triggerFileInput">选择图片</a-button>
        </template>
        <template v-else>
          <div style="display: flex; align-items: center;">
            <a-image :src="form.imageUrl" :preview="true" width="120" height="60" style="margin-right: 16px;" />
            <a-button type="primary" status="danger" size="mini" @click="removeImage">删除</a-button>
          </div>
        </template>
        <div style="color: #888; font-size: 12px; margin-top: 4px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;建议图片分辨率1920*1080</div>
      </a-form-item>

      <!-- 禁用模式选择 - 只在状态为禁用时显示 -->
      <a-form-item v-if="form.status === 0" label="禁用模式" required>
        <a-radio-group v-model="form.disableMode" direction="vertical">
          <a-radio value="default">使用默认禁用图片</a-radio>
          <a-radio value="custom">使用自定义禁用图片</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 自定义禁用图片上传 - 只在选择自定义模式时显示 -->
      <a-form-item v-if="form.status === 0 && form.disableMode === 'custom'" label="自定义禁用图片" required>
        <template v-if="!form.customDisableUrl">
          <input
            ref="disableFileInputRef"
            type="file"
            accept="image/jpeg,image/png,image/jpg"
            style="display: none;"
            @change="handleDisableImageUpload"
          />
          <a-button @click="triggerDisableFileInput">选择禁用图片</a-button>
        </template>
        <template v-else>
          <div style="display: flex; align-items: center;">
            <a-image :src="form.customDisableUrl" :preview="true" width="120" height="60" style="margin-right: 16px;" />
            <a-button type="primary" status="danger" size="mini" @click="removeDisableImage">删除</a-button>
          </div>
        </template>
        <div style="color: #888; font-size: 12px; margin-top: 4px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;建议图片分辨率1280*800，用于门口屏禁用显示</div>
      </a-form-item>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import http from '@/utils/http'
import { addMeetingRoom, getMeetingRoom, updateMeetingRoom } from '@/apis/meet/meetingRoom'
import type { Columns, GiForm, Options } from '@/components/GiForm'
import { useForm } from '@/hooks'
import { getBuildingList, getFactoryList } from '@/apis/common'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改会议室管理' : '新增会议室管理'))
const formRef = ref<InstanceType<typeof GiForm>>()
const fileInputRef = ref<HTMLInputElement | null>(null)
const disableFileInputRef = ref<HTMLInputElement | null>(null)

const options: Options = {
  form: {
    rules: {
      factorySiteId: [{ required: true, message: '所属厂区不能为空！' }],
      officeBuildingId: [{ required: true, message: '所属办公楼不能为空！' }],
      floor: [{ required: true, message: '所属楼层不能为空！' }],
      name: [{ required: true, message: '办公室名称不能为空！' }],
      capacity: [{ required: true, message: '会议室容量不能为空！' }]
      // imageUrl: [{ required: true, message: '会议室图片不能为空！' }] // 移除由手动校验
    }
  },
  btns: { hide: true }
}

const { form, resetForm } = useForm({
  id: '',
  factorySiteId: '',
  officeBuildingId: '',
  floor: '',
  name: '',
  capacity: '',
  imageUrl: '',
  status: 1,
  disableMode: 'default',
  customDisableUrl: ''
})

const columns = computed<Columns<typeof form>>(() => [
  {
    label: '所属厂区',
    field: 'factorySiteId',
    type: 'select',
    init: true,
    cascader: ['officeBuildingId'],
    request: getFactoryList,
    resultFormat(res) {
      return res.data.map((item) => ({ value: item.id, label: item.name }))
    },
    span: 24
  },
  {
    label: '所属办公楼',
    field: 'officeBuildingId',
    type: 'select',
    init: false,
    request: getBuildingList,
    resultFormat(res) {
      return res.data.map((item) => ({ value: item.id, label: item.name }))
    },
    span: 24
  },
  { label: '所属楼层', field: 'floor', type: 'input', span: 24 },
  { label: '办公室名称', field: 'name', type: 'input', span: 24 },
  { label: '会议室容量', field: 'capacity', type: 'input-number', span: 24 },
  {
    label: '状态',
    field: 'status',
    type: 'radio-group',
    options: [
      { label: '开启', value: 1 },
      { label: '禁用', value: 0 }
    ],
    span: 24
  }
])

// columnsWithoutImage 直接等于 columns
const columnsWithoutImage = columns

const triggerFileInput = () => {
  fileInputRef.value?.click()
}

const handleImageUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) {
    Message.error('请选择图片')
    return
  }
  if (file.size > 8 * 1024 * 1024) {
    Message.error('图片大小不能超过8MB')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  const loadingMsg = Message.loading({ content: '正在上传...', duration: 0 })
  try {
    const res = await http.post('/user/roomImg', formData)
    loadingMsg.close()
    if (String(res.code) === '0' || String(res.code) === '200') {
      form.imageUrl = typeof res.data === 'string' ? res.data : res.data.url
      Message.success('上传成功')
    } else {
      Message.error(res.msg || '上传失败')
    }
  } catch (error: any) {
    loadingMsg.close()
    Message.error(`上传失败：${error.message || '未知错误'}`)
  }
  // 重置input，允许重复上传相同文件
  if (fileInputRef.value) fileInputRef.value.value = ''
}

const removeImage = () => {
  form.imageUrl = ''
  if (fileInputRef.value) fileInputRef.value.value = ''
}

const triggerDisableFileInput = () => {
  disableFileInputRef.value?.click()
}

const handleDisableImageUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) {
    Message.error('请选择图片')
    return
  }
  if (file.size > 8 * 1024 * 1024) {
    Message.error('图片大小不能超过8MB')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  const loadingMsg = Message.loading({ content: '正在上传禁用图片...', duration: 0 })
  try {
    // 使用与会议室图片相同的上传接口
    const res = await http.post('/user/roomImg', formData)
    loadingMsg.close()
    if (String(res.code) === '0' || String(res.code) === '200') {
      form.customDisableUrl = typeof res.data === 'string' ? res.data : res.data.url
      Message.success('禁用图片上传成功')
    } else {
      Message.error(res.msg || '禁用图片上传失败')
    }
  } catch (error: any) {
    loadingMsg.close()
    Message.error(`禁用图片上传失败：${error.message || '未知错误'}`)
  }
  // 重置input，允许重复上传相同文件
  if (disableFileInputRef.value) disableFileInputRef.value.value = ''
}

const removeDisableImage = () => {
  form.customDisableUrl = ''
  if (disableFileInputRef.value) disableFileInputRef.value.value = ''
}

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
  form.imageUrl = ''
  form.customDisableUrl = ''
  if (fileInputRef.value) fileInputRef.value.value = ''
  if (disableFileInputRef.value) disableFileInputRef.value.value = ''
}

const visible = ref(false)

// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id, factoryId) => {
  reset()
  dataId.value = id
  const res = await getMeetingRoom(id)
  let name = res.data.name
  if (name.startsWith('（已禁用）')) {
    name = name.replace(/^（已禁用）/, '')
  }
  Object.assign(
    form,
    {
      ...res.data,
      id: res.data.id,
      factorySiteId: factoryId,
      officeBuildingId: Number(res.data.officeBuildingId),
      capacity: res.data.capacity,
      imageUrl: res.data.imageUrl || '',
      status: res.data.status,
      name,
      disableMode: res.data.disableMode || 'default',
      customDisableUrl: res.data.customDisableUrl || res.data.doorImgUrl || '' // 优先使用customDisableUrl，如果没有则使用doorImgUrl
    }
  )
  visible.value = true
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (!form.imageUrl) {
      Message.error('请上传会议室图片')
      return false
    }
    // 验证禁用模式相关字段
    if (form.status === 0 && form.disableMode === 'custom' && !form.customDisableUrl) {
      Message.error('选择自定义禁用模式时，请上传自定义禁用图片')
      return false
    }
    let name = form.name
    if (form.status === 0) {
      if (!name.startsWith('（已禁用）')) {
        name = `（已禁用）${name}`
      }
    } else {
      if (name.startsWith('（已禁用）')) {
        name = name.replace(/^（已禁用）/, '')
      }
    }
    const submitData: any = {
      name,
      floor: form.floor,
      capacity: Number(form.capacity),
      imageUrl: form.imageUrl,
      status: Number(form.status)
    }

    // 如果是禁用状态，添加禁用模式相关字段
    if (form.status === 0) {
      submitData.disableMode = form.disableMode
      if (form.disableMode === 'custom' && form.customDisableUrl) {
        submitData.customDisableUrl = form.customDisableUrl
      }
    }
    if (isUpdate.value) {
      submitData.id = Number(form.id)
      await updateMeetingRoom(submitData)
      Message.success('修改成功')
    } else {
      await addMeetingRoom(submitData)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>
